/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "interface/pcie_device/bandwidth.h"

namespace dev {

bool PCIeDevice_Bandwidth::update_link_ability_by_ncsi() {
    ncsi_link_ability_t link_ability = {};
    bool ret = m_ncsi_over_mctp_huawei->get_link_ability(DEFAULT_PACKAGE_ID, DEFAULT_CHANNEL_ID,
                                                         &link_ability);
    if (!ret) {
        elog("Error: Failed to update link ability");
        return false;
    }
    LinkWidthCapability.set_value(link_ability.link_width);
    LinkSpeedCapability.set_value(link_ability.link_speed);
    return true;
}

bool PCIeDevice_Bandwidth::update_link_info_by_ncsi() {
    ncsi_link_info_t link_info = {};
    bool             ret =
        m_ncsi_over_mctp_huawei->get_link_info(DEFAULT_PACKAGE_ID, DEFAULT_CHANNEL_ID, &link_info);
    if (!ret) {
        elog("Error: Failed to update link info");
        return false;
    }
    LinkWidth.set_value(link_info.link_width);
    LinkSpeed.set_value(link_info.link_speed);
    return true;
}

void PCIeDevice_Bandwidth::start_ncsi_update_task_huawei(ncsi_over_mctp_hw_ptr ncsi_over_mctp,
                                                         mc::milliseconds      interval) {
    m_ncsi_timer            = new mc::core::timer(this);
    m_ncsi_over_mctp_huawei = ncsi_over_mctp;
    m_ncsi_timer->timeout.connect([this]() {
        update_link_ability_by_ncsi();
        update_link_info_by_ncsi();
    });
    m_ncsi_timer->set_single_shot(false);
    m_ncsi_timer->start(interval);
}

void PCIeDevice_Bandwidth::stop_ncsi_update_task() {
    if (m_ncsi_timer) {
        m_ncsi_timer->stop();
        delete m_ncsi_timer;
        m_ncsi_timer = nullptr;
    }
    if (m_ncsi_over_mctp_huawei) {
        m_ncsi_over_mctp_huawei = nullptr;
    }
}

} // namespace dev

MC_REFLECT(dev::PCIeDevice_Bandwidth)